package steed.util.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.http.Part;

import steed.domain.GlobalParam;
import steed.exception.runtime.system.AttackedExeception;
import steed.util.base.BaseUtil;
import steed.util.base.PathUtil;
import steed.util.base.StringUtil;
import steed.util.digest.Md5Util;

/**
 * 单机模式文件引擎
 * @author 战马
 *
 */
public class StandAloneMachineFileEngine implements FileEngine{

	@Override
	public String upload(String key, File file) {
		return upload(key, file, key);
	}

	/*
	 * TODO 支持路径过期时间
	 */
	@Override
	public String getHttpUrl(String key, Long effectiveTime) {
		return getHttpUrl(key);
	}
	
	@Override
	public String getHttpUrl(String key, Date expireDate) {
		return getHttpUrl(key);
	}

	@Override
	public String getHttpUrl(String key) {
		return PathUtil.getBrowserPath(key);
	}
	
	

	@Override
	public boolean delete(String key) {
		return getFile(key).delete();
	}


	@Override
	public String upload(String key, File file, String fileName) {
		if (fileName == null) {
			fileName = key;
		}
		if (fileName.endsWith(".jsp")) {
			throw new AttackedExeception("请勿上传jsp文件!!!");
		}
		String path2 = getSaveRelativePath(key, fileName);
		String mergePath = getSaveAbsolutePath(path2);
		FileUtil.copyFile(file, mergePath);
		return path2;
	}

	private String getSaveAbsolutePath(String path2) {
		return PathUtil.mergePath(GlobalParam.FOLDER.rootPath, path2);
	}

	private String getSaveRelativePath(String key, String fileName) {
		return PathUtil.mergePath("upload/", key+FileUtil.getFileSuffix(fileName));
	}

	@Override
	public File getFile(String key) {
		return new File(getSaveAbsolutePath(key));
	}

//	@Override
//	public String upload(String key, Part part) {
//		String saveRelativePath = getSaveRelativePath(key, part.getSubmittedFileName());
//		try {
//			FileUtil.saveFile(saveRelativePath, part.getInputStream());
//		} catch (IOException e) {
//			BaseUtil.getLogger().error("上传文件失败",e);
//		}
//		return saveRelativePath;
//	}


}
